const jwt = require("jsonwebtoken");
// const { UnauthorizedError } = require("express-jwt");
const authenticate = (req, res, next) => {
  let list = ["/xspApi/login", "/xspApi/refresh-token"];
  if (list.length > 0 && list.indexOf(req._parsedUrl.pathname) >= 0) {
    return next();
  }
  const accessToken = req.headers["authorization"] || null;
  if (!accessToken) {
    // throw new UnauthorizedError("没有短Token哟！");
    return res.json({ code: 403, msg: "没有短Token哟！，请重新登陆" });
  }
  try {
    const decoded = jwt.verify(accessToken, "secret");
    if (req.user === decoded) {
      return next();
    }
    req.user = decoded;
    next()
  } catch (error) {
    // throw new UnauthorizedError("短Token无效！");
    return res.json({ code: 403, msg: "短Token无效！，请重新登陆" });
  }
};
module.exports = { authenticate };
